<!DOCTYPE html>
<html>

<head>
<meta charset="UTF-8">
<title>Expenditure Summary</title>
<script type="text/javascript" src="../js/d3.js"></script>
<script type="text/javascript" src="../js/dimple.v2.1.0.js"></script>
	<script type="text/javascript" src="../util/Navigator.js"></script>
<link href="../css/navigator.css" rel="stylesheet"/>

<style type="text/css">
	 body {
            text-align: center;
            margin: 0;
     }
     svg {
         font: 10px sans-serif;
     }
     .header {
         font: 15px sans-serif;
     }
     div.tooltip {
		  position: absolute;
		  text-align: left;
		  padding: 8px;
		  font: 10px sans-serif;
		  background: #ddd;
		  border: solid 1px #aaa;
		  border-radius: 8px;
		  pointer-events: none;
	}
</style>

</head>
<body>
	<!--<div style="font-size:20px;width:400px;margin-left:auto;margin-right:auto;">รายงานสถิติรายได้จากนักศึกษา</div>
	<div style="margin-left:auto;margin-right:auto;">
		<div style="display:inline-block;margin-left:5px;vertical-align:top;">
			<a href="../index.html"><img src="../images/home_icon.png"  width="50" height="50"></a>
		</div>
		<div style="display:inline-block;">
			<div id="chartContainer" style="display:inline-block;"></div>
		</div>
	</div>-->
	<!--<div id="chartContainer"></div>-->
	<!--<div id="donutChart"></div>-->
	<div id="header" style="position: fixed;width: 100%;background-color: rgb(255,255,255);"></div>
	<div id="navigator" style="position: fixed;width: 100%;top: 42px;background-color: rgb(255,255,255);"></div>
	<script type="text/javascript">
		var header = d3.select("#header").attr("class","header");
		header.html("<a href='../index.html'><img src='../images/home_icon.png'></a> รายงานสถิติรายได้จากนักศึกษา  ");
		
		var root = {"name":"รายได้แยกตามปี",
				"children":[{"name":"รายได้แยกตามคณะ"}]
		};
		navigator("navigator", root);		
		var navi = d3.select("#navigator").selectAll("g.node").selectAll("circle");
		navi.forEach(function(d,i){
			if(i==0){
				navi1 = d[0];
			}else{
				navi2 = d[0];
			}
		});
		navi1.style.fill = "rgb(176,196,222)";
		
		d3.select("body").append("div").attr("id","chartContainer");
		d3.select("body").append("div").attr("id","donutChart");
		var svg = dimple.newSvg("#chartContainer", 1000, 500);
		
		d3.json("../XPD001Controller",function(error,data){
			  data.forEach(function(d){
				  if(d["studyPeriod"]=="1"){
					  d["Period"] = "ภาคปกติ";
				  }else if(d["studyPeriod"]=="2"){
					  d["Period"] = "ภาคพิเศษ";
				  }else{
					  d["Period"] = "รวมทั้งหมด";
				  }
				  d["ปี"] = d["acadYear"];
				  d["จำนวนเงิน"] = d["amount"];
			  },this)
			  
			  //console.log(data);
			  
			  var myChart = new dimple.chart(svg, data);
		      myChart.setBounds(60, 100, 960, 300);
		      var x = myChart.addCategoryAxis("x", "ปี");
		      myChart.addMeasureAxis("y", "จำนวนเงิน");
		      myChart.addMeasureAxis("z", "จำนวนเงิน");
		     
		      x.addOrderRule("ปี");
		      
		      var lines = myChart.addSeries("Period", dimple.plot.line); 
		      lines.lineWeight = 3;
		      lines.lineMarkers = true;
		      
		      lines.addEventHandler("click", onClick);
		      
		      myChart.addLegend(600, 10, 360, 20, "right");
		      myChart.draw(600);
		      
		      function onClick(e) {
		    	  fistDrilldown(e.xValue,e.seriesValue[0]);
		    	  /* console.log(e);
		    	  console.log(e.xValue);
		    	  cons ole.log(e.seriesValue[0]);*/
		      }
		      
		});//end d3 json
		
		function fistDrilldown(acadYear,stdPeriod){
			navi2.style.fill = "rgb(176,196,222)";
			if(document.getElementById("donut")!=null){
				document.getElementById("donut").remove();
			}
			d3.json("../XPD001Controller?acadYear="+acadYear+"&stdPeriod="+stdPeriod,function(error,data){
				var m = 100,
                r = 100,
                id = 0,
                count = 0,
                z = d3.scale.category20();

            	var position = Math.PI / 180;
            	
            	var pie = d3.layout.pie()
                .value(function(d) {
                    return +d.amount;
                })
                .sort(null);
            	
            	var arc = d3.svg.arc()
                .innerRadius(r / 2)
                .outerRadius(r);
            	
            	var data = d3.nest()
                .key(function(d) {
                    return d.acadYear;
                })
                .entries(data);
                
            	 var svg = d3.select("#donutChart").selectAll("div")
                 .data(data)
                 .enter()
                 .append("div")
                 .attr("id","donut")
                 .style("display", "inline")
                 .style("width", 1024 + "px")
                 .style("height", 764 + "px")
                 .append("svg:svg")
                 .attr("width", (r + m) * 6)
                 .attr("height", (r + m) * 4)
                 .append("svg:g")
                 .attr("transform", "translate(" + ((r + m)*2) + "," + ((r + m)*1.5) + ")");
                
            	 svg.append("svg:text")
                 .attr("dy", ".35em")
                 .attr("text-anchor", "middle")
                 .text(function(d) {
                     return d.key;
                 });
            	 
            	 var g = svg.selectAll("g")
                 .data(function(d) {
                     return pie(d.values);
                 })
                 .enter().append("svg:g");
            	 
            	 g.append("svg:path")
                 .attr("class", "arc")
                 .attr("id",function(d){
                	 return "arc-"+(id++);
                 })
                 .attr("arc-id",function(d){
                	 return count++;
                 })
                 .style("fill", function(d) {
                     return z(d.data.facName);
                 })
                 //.on("click",function(d) {firstDrilldown(d.data.rewardId,d.data.rewardName);})
                 .on("mouseover", mouseover)
                 .on("mouseout", mouseout)
                 .transition()
                 .ease("exp")
                 .ease("bounce")
                 .duration(2500)
                 .delay(function(d, i) {
                     return i * 10;
                 })
                 .attrTween("d", tweenPie);
            	 
            	 function tweenPie(b) {
                     var i = d3.interpolate({
                         startAngle: -30 * position,
                         endAngle: -31 * position
                     }, b);
                     return function(t) {
                         return arc(i(t));
                     };
                 }
            	 
            	 //append tooltip
            	 var tip = d3.select("body").append("div")
            	    .attr("class", "tooltip")
            	    .style("opacity", 1e-6);
            	 
				 var legentLink;
				 
            	function mouseover(d) {
            	  legentLink = d3.select("#legend-"+d3.select(this).attr("arc-id"));
            	  legentLink.style("opacity", 0.3);
            	  tip.transition().duration(500).style("opacity", 1);
            	  tip.html("คณะ: "+d.data.facName+"<br/> จำนวนเงิน: "+d.data.amount.toLocaleString("th-TH"))
                  .style("left", (d3.event.pageX - 34) + "px")
                  .style("top", (d3.event.pageY - 12) + "px");
            	}
            	
            	function mouseout() {
            		tip.transition().duration(500).style("opacity", 1e-6);
            		legentLink.style("opacity", 1);
            	}

            	var pos = d3.svg.arc().innerRadius(r+10).outerRadius(r+10);
                 //line for label
                /*  var ticks = svg.selectAll("line")
                     .data(function(d) {
                         return pie(d.values);
                     })
                     .enter()
                     .append("line");
                 ticks.attr("x1", 0)
                     .attr("x2", 0)
                     .attr("y1", -r + 4)
                     .attr("y2", -r - 15)
                     .attr("stroke", "gray")
                     .transition()
                     .ease("exp")
                     .ease("bounce")
                     .duration(2500)
                     .attr("transform", function(d) {
                         return "rotate(" + (d.startAngle + d.endAngle) / 2 * (180 / Math.PI) + ")";
                     }); */
                 
                 g.append("svg:text")
                 	.attr("dy", ".35em")
					.attr("text-anchor", positionLabel)
                 //.attr("transform", function(d) {return "translate(" + pos.centroid(d) + ")";})
                 .text(function(d) {
                     return d.data.facName;
                 })
                 .transition()
                 .ease("exp")
                 .ease("bounce")
                 .duration(2500)
                 .delay(function(d, i) {
                     return i * 10;
                 })
                 .attrTween("transform", tweenText); 
                 
                 function tweenText(b) {
                     var i = d3.interpolate({
                         startAngle: -30 * position,
                         endAngle: -31 * position
                     }, b);
                     return function(t) {
                         return "translate(" + pos.centroid(i(t)) + ")rotate("+angle(i(t))+")";
                     };
                 }
                 
                 var getAngle = function (d) {
                     return (180 / Math.PI * (d.startAngle + d.endAngle) / 2 - 90);
                 };
                 
                 g.append("svg:text")
                 .attr("dy", ".35em")
                 .attr("text-anchor", "middle")
                 //.attr("transform", function(d) {return "translate(" + arc.centroid(d) + ")";})
                 .text(function(d) {
                     return (d.data.amount/1000000).toFixed(2) + "m";
                 })
                 .transition()
                 .ease("exp")
                 .ease("bounce")
                 .duration(2500)
                 .delay(function(d, i) {
                     return i * 10;
                 })
                 //calulate text rander to each arc
                 .each(function(d){
                	 var bb = this.getBBox(),
                     center = arc.centroid(d);
                     
	                 var topLeft = {
	                   x : center[0] + bb.x,
	                   y : center[1] + bb.y
	                 };
	                 
	                 var topRight = {
	                   x : topLeft.x + bb.width,
	                   y : topLeft.y
	                 };
	                 
	                 var bottomLeft = {
	                   x : topLeft.x,
	                   y : topLeft.y + bb.height
	                 };
	                 
	                 var bottomRight = {
	                   x : topLeft.x + bb.width,
	                   y : topLeft.y + bb.height
	                 };
	                 
	                 d.visible = pointIsInArc(topLeft, d, arc) &&
	                             pointIsInArc(topRight, d, arc) &&
	                             pointIsInArc(bottomLeft, d, arc) &&
	                             pointIsInArc(bottomRight, d, arc);
                 })
                 .style('display', function (d) { return d.visible ? null : "none"; })
                 
                 .attrTween("transform", tweenAmount);
            	 
                 function tweenAmount(b) {
                     var i = d3.interpolate({
                         startAngle: -30 * position,
                         endAngle: -31 * position
                     }, b);
                     return function(t) {
                         //return "translate(" + arc.centroid(i(t)) + ")rotate("+angle(i(t))+")";
                    	 return "translate(" + arc.centroid(i(t)) + ")";
                     };
                 }
                 
                 function pointIsInArc(pt, ptData, d3Arc) {
               	    // Center of the arc is assumed to be 0,0
               	    // (pt.x, pt.y) are assumed to be relative to the center
               	    var r1 = arc.innerRadius()(ptData),
               	        r2 = arc.outerRadius()(ptData),
               	        theta1 = arc.startAngle()(ptData),
               	        theta2 = arc.endAngle()(ptData);
               	    
               	    var dist = pt.x * pt.x + pt.y * pt.y,
               	        angle = Math.atan2(pt.x, -pt.y);
               	    
               	    angle = (angle < 0) ? (angle + Math.PI * 2) : angle;
               	        
               	    return (r1 * r1 <= dist) && (dist <= r2 * r2) && 
               	           (theta1 <= angle) && (angle <= theta2);
                }
                 
                 function angle(d) {
                     var a = (d.startAngle + d.endAngle) * 90 / Math.PI - 90;
                     return a > 90 ? a - 180 : a;
                 }
                 
                 function positionLabel(d){
                	 var a = (d.startAngle + d.endAngle) * 90 / Math.PI - 90;
                	 return a > 90 ? "end":"start";
                 }
                 
                 //legend
                 id=0;
                 count=0;
                 var arc;
                 var legend = svg.selectAll(".legend")
                 .data(function(d){
                	 return d.values;
                 }).enter()
                 .append("g").attr("class", "legend")
                 .attr("id",function(d){
                	 return "legend-"+ id++;
                 })
                 .attr("legend-id", function(d) {
                     return count++;
                 })
                 .attr("transform", function(d, i) {
                     return "translate(-10," + (-70 + i * 20) + ")";
                 })
                 .on("mouseover", function() {
                     //console.log("#arc-" + d3.select(this).attr("legend-id"));
                     arc = d3.select("#arc-" + d3.select(this).attr("legend-id"));
                     arc.style("opacity", 0.3);
                 })
                 .on("mouseout",function(){
                	arc.style("opacity",1); 
                 });
             
             	legend.append("rect")
                 .attr("x", 1040 / 2)
                 .attr("width", 18).attr("height", 18)
                 .style("fill", function(d) {
                     return z(d.facName);
                 });
             	
             	legend.append("text").attr("x", 1024 / 2)
                 .attr("y", 9).attr("dy", ".35em")
                 .style("text-anchor", "end").text(function(d) {
                     return d.facName;
                 });
                 
			});//end d3 json
			goToAnchor("donutChart");
		}//end firstdrilldown
		
		function goToAnchor(name) {
		    //var top = document.getElementById(name).offsetTop;
		    //window.scrollTo(0, top);
		    document.getElementById(name).scrollIntoView(true);
		}
	</script>
</body>
</html>